from handlers import BaseHandler
from model import HostComputer
from tornado.gen import coroutine
from forms import CreateUserForm
from utils.multithreading import executor
from tornado.stack_context import wrap


class HostHandler(BaseHandler):
    @coroutine
    def get(self):
        query = self.session.query(HostComputer)
        hosts = yield executor(query.all)
        response = []
        for host in hosts:
            response.append(host.to_dict())
        self.finish({"status": True, "response": response})

    @coroutine
    def post(self):
        form = CreateUserForm(self.request.arguments)
        if form.validate():
            data = form.data
            if form.data['id'] == None:
                host = HostComputer(**data)
                self.session.add(host)
                yield executor(wrap(self.session.commit))
            else:
                query = self.session.query(HostComputer).filter_by(id=form.data["id"])
                host = yield executor(wrap(query.first))
                host.update_value(**data)
                yield executor(wrap(self.session.commit))
            self.finish({"status": True, 'response': host.to_dict()})
        else:
            self.finish({"status": False, 'response': form.errors})

    @coroutine
    def delete(self):
        id = self.get_argument("id")
        query = self.session.query(HostComputer).filter_by(id=id)
        host = yield executor(query.first)
        self.session.delete(host)
        yield executor(wrap(self.session.commit), *())
        self.finish({"status": True, 'response': host.to_dict()})
